<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin:0;padding:0;
        }
        html,body,#app{
            height: 100%;
            width: 100%;
            overflow: hidden;
            position:relative;
        }
        #move{
            width: 150px;
            height: 150px;
            background:#aef;
            position:absolute;
            /* transition: all 0.3s; */
        }
    </style>
</head>
<body>
    <div id="app">
        <div id="move"></div>        
    </div>

    <script>
        let move = document.querySelector('#move');

        //触摸开始
        move.addEventListener('touchstart', function(e){
            //获取元素相对于父级元素的 x 轴偏移量
            this.l = this.offsetLeft;
            //获取触点
            this.x = e.changedTouches[0].pageX;

            this.t = this.offsetTop;
            this.y = e.changedTouches[0].pageY;
            //移除过渡
            this.style.transition = 'none';

        });

        move.addEventListener('touchmove', function(e){
            //获取手指滑动之后, x 轴的偏移量
            let _x = e.changedTouches[0].pageX;
            let _y = e.changedTouches[0].pageY;

            //计算新的 left 的值
            let newLeft = _x - (this.x - this.l);
            let newTop = _y - (this.y - this.t);

            //判断 newLeft 的值
            if(newLeft <= 0) newLeft = 0;
            //
            let maxLeft = this.maxLeft = app.offsetWidth - this.offsetWidth;
            //判断 
            if(newLeft >= maxLeft) newLeft = maxLeft;
            //设置
            this.style.left = newLeft + 'px';
            this.style.top = newTop + 'px';
        });

        move.addEventListener('touchend', function(e){
            ///增加过渡
            this.style.transition = 'all 0.5s';
            //判断
            //获取元素此时的 x 轴偏移量  this.style.left    100px  => 100   parseInt
            let l = this.offsetLeft;
            //判断居左还是居右
            let middle = (app.offsetWidth - this.offsetWidth) / 2;
            //判断 
            if(l < middle){
                this.style.left = '0px';
            }else{
                this.style.left = this.maxLeft + 'px';
            }
        });

    </script>
</body>
</html>